<template>
  <div :class="['manus-message', { 'user-message': isUser, 'ai-message': !isUser }]">
    <div class="message-avatar">
      <div class="avatar">
        {{ isUser ? '👤' : '🤖' }}
      </div>
    </div>
    <div class="message-content">
      <div class="message-bubble">
        <!-- 用户消息直接显示 -->
        <div v-if="isUser" class="message-text">{{ content }}</div>
        
        <!-- AI消息解析显示 -->
        <div v-else class="ai-response">
          <!-- 步骤流程 -->
          <div v-if="parsedSteps.length > 0" class="steps-container">
            <div class="steps-header">
              <span class="steps-icon">⚡</span>
              <span class="steps-title">执行流程</span>
            </div>
            <div class="steps-list">
              <div 
                v-for="(step, index) in parsedSteps" 
                :key="index"
                class="step-item"
                :class="{ 'completed': step.completed }"
              >
                <div class="step-indicator">
                  <span class="step-number">{{ index + 1 }}</span>
                  <span v-if="step.completed" class="step-check">✓</span>
                </div>
                <div class="step-content">
                  <div class="step-title">{{ step.title }}</div>
                  <div v-if="step.description" class="step-description">{{ step.description }}</div>
                  
                  <!-- 搜索结果展示 -->
                  <div v-if="step.searchResults" class="search-results">
                    <div class="results-header">
                      <span class="results-icon">🔍</span>
                      <span>找到 {{ step.searchResults.length }} 个相关结果</span>
                    </div>
                    <div class="results-list">
                      <div 
                        v-for="(result, resultIndex) in step.searchResults.slice(0, 3)" 
                        :key="resultIndex"
                        class="result-item"
                      >
                        <div class="result-thumbnail" v-if="result.thumbnail">
                          <img :src="result.thumbnail" :alt="result.title" @error="handleImageError">
                        </div>
                        <div class="result-content">
                          <h4 class="result-title">
                            <a :href="result.link" target="_blank" rel="noopener noreferrer">
                              {{ result.title }}
                            </a>
                          </h4>
                          <p class="result-snippet">{{ result.snippet }}</p>
                          <div class="result-meta">
                            <span class="result-source">{{ result.displayed_link }}</span>
                            <span v-if="result.date" class="result-date">{{ result.date }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 展开更多结果 -->
                    <button 
                      v-if="step.searchResults.length > 3" 
                      @click="toggleMoreResults(index)"
                      class="show-more-btn"
                    >
                      {{ step.showMore ? '收起' : `查看更多 (${step.searchResults.length - 3} 个)` }}
                    </button>
                    
                    <!-- 更多结果 -->
                    <div v-if="step.showMore" class="more-results">
                      <div 
                        v-for="(result, resultIndex) in step.searchResults.slice(3)" 
                        :key="`more-${resultIndex}`"
                        class="result-item"
                      >
                        <div class="result-thumbnail" v-if="result.thumbnail">
                          <img :src="result.thumbnail" :alt="result.title" @error="handleImageError">
                        </div>
                        <div class="result-content">
                          <h4 class="result-title">
                            <a :href="result.link" target="_blank" rel="noopener noreferrer">
                              {{ result.title }}
                            </a>
                          </h4>
                          <p class="result-snippet">{{ result.snippet }}</p>
                          <div class="result-meta">
                            <span class="result-source">{{ result.displayed_link }}</span>
                            <span v-if="result.date" class="result-date">{{ result.date }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 原始数据展示（JSON解析失败时的备用显示） -->
                  <div v-else-if="step.rawData" class="raw-data">
                    <div class="raw-data-header">
                      <span class="raw-data-icon">📋</span>
                      <span>原始返回数据</span>
                    </div>
                    <div class="raw-data-content">
                      <pre>{{ step.rawData }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Markdown渲染的消息 -->
          <div v-else class="markdown-content" v-html="renderedMarkdown"></div>
          
          <!-- 调试信息 -->
          <div v-if="!isUser && parsedSteps.length === 0 && content.includes('Step')" class="debug-info">
            <div class="debug-header">
              <span class="debug-icon">🔍</span>
              <span>调试信息：步骤解析失败</span>
            </div>
            <div class="debug-content">
              <p>检测到Step格式内容但解析失败，显示原始内容：</p>
              <div class="original-content">
                <pre>{{ content }}</pre>
              </div>
            </div>
          </div>
        </div>
        
        <div class="message-time">{{ formatTime(timestamp) }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 配置marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (err) {}
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true,
  gfm: true,
  tables: true,
  sanitize: false
})

export default {
  name: 'ManusMessage',
  props: {
    content: {
      type: String,
      required: true
    },
    isUser: {
      type: Boolean,
      default: false
    },
    timestamp: {
      type: Date,
      default: () => new Date()
    }
  },
  data() {
    return {
      parsedSteps: []
    }
  },
  computed: {
    formattedContent() {
      return this.content.replace(/\n/g, '<br>')
    },
    renderedMarkdown() {
      if (this.isUser) {
        return this.formattedContent
      }
      
      // 对于AI消息，如果包含Step格式且成功解析，则不进行markdown渲染
      if (this.content.includes('Step ') && this.parsedSteps.length > 0) {
        return this.formattedContent
      }
      
      // 否则进行markdown渲染
      try {
        return marked(this.content)
      } catch (error) {
        console.error('Markdown渲染失败:', error)
        return this.formattedContent
      }
    }
  },
  watch: {
    content: {
      immediate: true,
      handler(newContent) {
        if (!this.isUser) {
          this.parseAiResponse(newContent)
        }
      }
    }
  },
  methods: {
    parseAiResponse(content) {
      this.parsedSteps = []
      
      console.log('开始解析AI响应:', content.substring(0, 200))
      
      // 解析Step格式的内容
      const stepRegex = /Step (\d+):\s*(.*?)(?=Step \d+:|$)/gs
      const matches = [...content.matchAll(stepRegex)]
      
      console.log('找到Step匹配数量:', matches.length)
      
      if (matches.length > 0) {
        matches.forEach((match, index) => {
          const stepNumber = parseInt(match[1])
          const stepContent = match[2].trim()
          
          const step = {
            number: stepNumber,
            completed: true,
            showMore: false
          }
          
          console.log(`解析Step ${stepNumber}:`, stepContent.substring(0, 100))
          
          // 解析工具调用
          if (stepContent.includes('工具') && stepContent.includes('完成了它的任务')) {
            const toolMatch = stepContent.match(/工具\s+(\w+)\s+完成了它的任务！结果:\s*"?(.*?)"?$/s)
            if (toolMatch) {
              const toolName = toolMatch[1]
              const resultData = toolMatch[2]
              
              step.title = `${toolName} 工具执行`
              step.description = `${toolName} 工具已成功完成任务`
              
              // 解析搜索结果
              if (toolName === 'searchWeb') {
                step.searchResults = this.parseSearchResults(resultData)
                if (!step.searchResults) {
                  step.rawData = resultData.length > 500 ? resultData.substring(0, 500) + '...' : resultData
                }
              }
            }
          } else if (stepContent.includes('思考完成')) {
            step.title = '思考分析'
            step.description = '正在分析问题并制定解决方案'
          } else if (stepContent.includes('doTerminate')) {
            step.title = '任务完成'
            step.description = '所有步骤已完成，任务结束'
          } else {
            step.title = `步骤 ${stepNumber}`
            step.description = stepContent
          }
          
          this.parsedSteps.push(step)
          console.log(`添加步骤 ${stepNumber}:`, step.title)
        })
        
        console.log('最终解析的步骤数量:', this.parsedSteps.length)
      } else {
        console.log('未找到Step格式内容，尝试显示原始文本')
      }
    },
    
    parseSearchResults(data) {
      console.log('开始解析搜索结果，原始数据长度:', data.length)
      console.log('原始数据前200字符:', data.substring(0, 200))
      
      try {
        // 清理数据
        let cleanedData = data.trim()
        
        // 尝试多种解析策略
        const strategies = [
          // 策略1：直接解析
          () => JSON.parse(cleanedData),
          
          // 策略2：去除外层引号
          () => {
            if (cleanedData.startsWith('"') && cleanedData.endsWith('"')) {
              return JSON.parse(cleanedData.slice(1, -1))
            }
            throw new Error('No outer quotes')
          },
          
          // 策略3：处理转义字符
          () => {
            if (cleanedData.startsWith('"') && cleanedData.endsWith('"')) {
              const unescaped = cleanedData.slice(1, -1)
                .replace(/\\"/g, '"')
                .replace(/\\\\/g, '\\')
                .replace(/\\n/g, '\n')
                .replace(/\\r/g, '\r')
                .replace(/\\t/g, '\t')
              return JSON.parse(unescaped)
            }
            throw new Error('No outer quotes for unescape')
          },
          
          // 策略4：尝试查找JSON数组的起始位置
          () => {
            const arrayStart = cleanedData.indexOf('[')
            const arrayEnd = cleanedData.lastIndexOf(']')
            if (arrayStart !== -1 && arrayEnd !== -1 && arrayEnd > arrayStart) {
              const jsonPart = cleanedData.substring(arrayStart, arrayEnd + 1)
              return JSON.parse(jsonPart)
            }
            throw new Error('No array found')
          },
          
          // 策略5：尝试查找JSON对象的起始位置（对于单个对象）
          () => {
            const objectStart = cleanedData.indexOf('{')
            const objectEnd = cleanedData.lastIndexOf('}')
            if (objectStart !== -1 && objectEnd !== -1 && objectEnd > objectStart) {
              const jsonPart = cleanedData.substring(objectStart, objectEnd + 1)
              const parsed = JSON.parse(jsonPart)
              return Array.isArray(parsed) ? parsed : [parsed]
            }
            throw new Error('No object found')
          }
        ]
        
        // 尝试每种策略
        for (let i = 0; i < strategies.length; i++) {
          try {
            const result = strategies[i]()
            if (Array.isArray(result) && result.length > 0) {
              console.log(`策略 ${i + 1} 成功解析，找到 ${result.length} 个结果`)
              return result
            }
          } catch (e) {
            console.log(`策略 ${i + 1} 失败:`, e.message)
          }
        }
        
        console.error('所有解析策略都失败了')
        return null
        
      } catch (error) {
        console.error('搜索结果解析完全失败:', error)
        return null
      }
    },
    
    toggleMoreResults(stepIndex) {
      this.parsedSteps[stepIndex].showMore = !this.parsedSteps[stepIndex].showMore
    },
    
    handleImageError(event) {
      event.target.style.display = 'none'
    },
    
    formatTime(date) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    }
  }
}
</script>

<style scoped>
.manus-message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-in;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  margin: 0 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
}

.user-message .avatar {
  background: linear-gradient(45deg, #764ba2, #667eea);
}

.message-content {
  flex: 1;
  max-width: 80%;
}

.message-bubble {
  padding: 16px 20px;
  border-radius: 18px;
  position: relative;
}

.ai-message .message-bubble {
  background: #f8f9fa;
  border-bottom-left-radius: 6px;
}

.user-message .message-bubble {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  border-bottom-right-radius: 6px;
}

.message-text {
  line-height: 1.6;
  word-wrap: break-word;
}

.ai-response {
  line-height: 1.6;
}

/* 步骤流程样式 */
.steps-container {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.steps-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e9ecef;
}

.steps-icon {
  font-size: 1.2rem;
  margin-right: 8px;
}

.steps-title {
  font-weight: 600;
  color: #2c3e50;
  font-size: 1.1rem;
}

.steps-list {
  position: relative;
}

.step-item {
  display: flex;
  margin-bottom: 20px;
  position: relative;
}

.step-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 15px;
  top: 40px;
  width: 2px;
  height: calc(100% - 20px);
  background: #e9ecef;
}

.step-item.completed::after {
  background: #28a745;
}

.step-indicator {
  position: relative;
  margin-right: 16px;
  flex-shrink: 0;
}

.step-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #28a745;
  color: white;
  font-weight: 600;
  font-size: 0.9rem;
}

.step-check {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #28a745;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
}

.step-content {
  flex: 1;
}

.step-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
  font-size: 1rem;
}

.step-description {
  color: #6c757d;
  font-size: 0.9rem;
  margin-bottom: 12px;
}

/* 搜索结果样式 */
.search-results {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-top: 12px;
}

.results-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
  color: #495057;
}

.results-icon {
  margin-right: 8px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.result-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.result-thumbnail {
  flex-shrink: 0;
  margin-right: 12px;
}

.result-thumbnail img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-title {
  margin: 0 0 8px 0;
  font-size: 0.95rem;
  line-height: 1.3;
}

.result-title a {
  color: #1a73e8;
  text-decoration: none;
  font-weight: 500;
}

.result-title a:hover {
  text-decoration: underline;
}

.result-snippet {
  color: #5f6368;
  font-size: 0.85rem;
  line-height: 1.4;
  margin: 0 0 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-meta {
  display: flex;
  gap: 12px;
  font-size: 0.75rem;
  color: #70757a;
}

.result-source {
  color: #1a73e8;
  font-weight: 500;
}

.show-more-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.85rem;
  margin-top: 12px;
  transition: background 0.3s ease;
}

.show-more-btn:hover {
  background: #5a6fd8;
}

.more-results {
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 原始数据样式 */
.raw-data {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-top: 12px;
  border-left: 4px solid #ffc107;
}

.raw-data-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  color: #856404;
}

.raw-data-icon {
  margin-right: 8px;
}

.raw-data-content {
  background: white;
  border-radius: 4px;
  padding: 12px;
  border: 1px solid #dee2e6;
}

.raw-data-content pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.85rem;
  color: #495057;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
}

/* 调试信息样式 */
.debug-info {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 16px;
  margin-top: 12px;
}

.debug-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  color: #856404;
}

.debug-icon {
  margin-right: 8px;
}

.debug-content p {
  margin: 0 0 12px 0;
  color: #856404;
}

.original-content {
  background: white;
  border-radius: 4px;
  padding: 12px;
  border: 1px solid #dee2e6;
  max-height: 300px;
  overflow-y: auto;
}

.original-content pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.85rem;
  color: #495057;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* Markdown内容样式 */
.markdown-content {
  line-height: 1.6;
  word-wrap: break-word;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #2c3e50;
}

.markdown-content h1 { font-size: 1.5rem; }
.markdown-content h2 { font-size: 1.3rem; }
.markdown-content h3 { font-size: 1.1rem; }

.markdown-content p {
  margin: 8px 0;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content blockquote {
  border-left: 4px solid #ddd;
  margin: 16px 0;
  padding: 8px 16px;
  background: #f8f9fa;
  color: #6c757d;
}

.markdown-content code {
  background: #f1f3f4;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
  color: #e83e8c;
}

.markdown-content pre {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
  margin: 12px 0;
}

.markdown-content pre code {
  background: none;
  padding: 0;
  color: inherit;
  font-size: 0.85rem;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.markdown-content th,
.markdown-content td {
  border: 1px solid #dee2e6;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content th {
  background: #f8f9fa;
  font-weight: 600;
}

.markdown-content a {
  color: #1a73e8;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.markdown-content strong {
  font-weight: 600;
}

.markdown-content em {
  font-style: italic;
}

.markdown-content hr {
  border: none;
  border-top: 1px solid #dee2e6;
  margin: 16px 0;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.7;
  margin-top: 8px;
  text-align: right;
}

.ai-message .message-time {
  text-align: left;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .message-content {
    max-width: 90%;
  }
  
  .avatar {
    width: 32px;
    height: 32px;
    font-size: 16px;
  }
  
  .result-item {
    flex-direction: column;
  }
  
  .result-thumbnail {
    margin-right: 0;
    margin-bottom: 8px;
    align-self: center;
  }
  
  .steps-container {
    padding: 12px;
  }
}
</style>